from django.db import models
from django_cryptography.fields import encrypt

# Create your models here.
"""
深圳
├── 机房A
│   ├── 主机1
│   └── 主机2
└── 机房B
    ├── 主机3
    └── 主机4
"""


# 城市信息
class City(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.name


# 机房信息
class IDC(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    city = models.ForeignKey(City, on_delete=models.CASCADE, related_name='idcs')

    def __str__(self):
        return f"{self.name} ({self.city})"


# 主机信息
class Host(models.Model):
    id = models.AutoField(primary_key=True)
    hostname = models.CharField(max_length=100)
    ip = models.GenericIPAddressField()
    idc = models.ForeignKey(IDC, on_delete=models.CASCADE, related_name='hosts')
    root_password = encrypt(models.CharField(max_length=100, default='123456'))
    password_updated_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.hostname} {self.ip}"


# 按城市和机房维度统计主机数量
class HostStatistic(models.Model):
    date = models.DateField(auto_now_add=True)  # 统计日期
    city = models.ForeignKey(City, on_delete=models.CASCADE)  # 关联城市
    idc = models.ForeignKey(IDC, on_delete=models.CASCADE)  # 关联机房
    host_count = models.PositiveIntegerField()  # 主机数量

    def __str__(self):
        return f"{self.date} | {self.city.name} - {self.idc.name}: {self.host_count}"
